import React, { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Grid,
  Chip,
  Avatar,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  CircularProgress,
  Alert
} from '@mui/material';
import {
  LocalShipping as CarIcon,
  Search as SearchIcon,
  GpsFixed as LocationIcon,
  Add as AddIcon
} from '@mui/icons-material';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { mockVehicles } from '../data/mockVehicles';

const API_BASE_URL = 'http://localhost:8080/vehicle-secure';

const VehicleList = () => {
  const [vehicles, setVehicles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedVehicle, setSelectedVehicle] = useState(null);
  const [openDialog, setOpenDialog] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState('ALL');
  const navigate = useNavigate();

  // 获取认证token
  const getAuthHeader = () => {
    const token = localStorage.getItem('token');
    return token ? { Authorization: `Bearer ${token}` } : {};
  };

  // 获取车辆列表
  const fetchVehicles = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      const headers = getAuthHeader();
      console.log('Headers:', headers);
      
      if (!headers.Authorization) {
        console.log('未找到token，使用模拟数据');
        setVehicles(mockVehicles);
        setLoading(false);
        return;
      }

      try {
        // 根据用户角色获取不同的车辆列表
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        const endpoint = userInfo.role === 'ADMIN' 
          ? `${API_BASE_URL}/api/vehicles` 
          : `${API_BASE_URL}/api/vehicles/my`;
        
        console.log('请求端点:', endpoint);
        const response = await axios.get(endpoint, { 
          headers,
          timeout: 5000
        });
        
        if (response.data && Array.isArray(response.data)) {
          setVehicles(response.data);
          console.log('成功获取车辆数据:', response.data.length, '条');
        } else {
          console.log('返回数据格式不正确，使用模拟数据');
          setVehicles(mockVehicles);
        }
      } catch (apiError) {
        console.log('API调用失败:', apiError.message);
        setVehicles(mockVehicles);
      }
      
      setError(null);
    } catch (err) {
      console.error('获取车辆失败:', err);
      setError(`获取车辆信息失败: ${err.message}，显示演示数据`);
      setVehicles(mockVehicles);
    } finally {
      setLoading(false);
    }
  }, []);

  // 搜索车辆
  const searchVehicles = async () => {
    if (!searchTerm.trim()) {
      fetchVehicles();
      return;
    }

    try {
      setLoading(true);
      const headers = getAuthHeader();
      
      // 在模拟数据中进行搜索
      const filtered = mockVehicles.filter(vehicle => {
        const lowerQuery = searchTerm.toLowerCase();
        return (
          vehicle.vin?.toLowerCase().includes(lowerQuery) ||
          vehicle.licensePlate?.toLowerCase().includes(lowerQuery) ||
          vehicle.brand?.toLowerCase().includes(lowerQuery) ||
          vehicle.model?.toLowerCase().includes(lowerQuery) ||
          vehicle.ownerName?.toLowerCase().includes(lowerQuery)
        );
      });
      
      setVehicles(filtered);
    } catch (err) {
      setError('搜索失败');
    } finally {
      setLoading(false);
    }
  };

  // 删除车辆
  const deleteVehicle = async (vehicleId) => {
    if (!window.confirm('确定要删除这辆车吗？')) return;
    
    try {
      const headers = getAuthHeader();
      await axios.delete(`${API_BASE_URL}/api/vehicles/${vehicleId}`, { headers });
      fetchVehicles(); // 重新加载列表
    } catch (err) {
      setError('删除车辆失败');
    }
  };

  // 标记车辆状态
  const updateVehicleStatus = async (vehicleId, status) => {
    try {
      const headers = getAuthHeader();
      const endpoint = status === 'STOLEN' 
        ? `${API_BASE_URL}/api/vehicles/${vehicleId}/mark-stolen`
        : `${API_BASE_URL}/api/vehicles/${vehicleId}/unmark-stolen`;
      
      await axios.post(endpoint, {}, { headers });
      fetchVehicles(); // 重新加载列表
    } catch (err) {
      setError('更新车辆状态失败');
    }
  };

  // 获取车辆状态颜色
  const getStatusColor = (status) => {
    switch (status) {
      case 'ACTIVE': return 'success';
      case 'STOLEN': return 'error';
      case 'MAINTENANCE': return 'warning';
      case 'INACTIVE': return 'default';
      default: return 'info';
    }
  };

  // 获取状态中文名
  const getStatusLabel = (status) => {
    switch (status) {
      case 'ACTIVE': return '正常';
      case 'STOLEN': return '被盗';
      case 'MAINTENANCE': return '维修中';
      case 'INACTIVE': return '停用';
      default: return status;
    }
  };

  useEffect(() => {
    fetchVehicles();
  }, [fetchVehicles]);

  const filteredVehicles = vehicles.filter(vehicle => {
    const matchesSearch = searchTerm === '' || 
      vehicle.vin?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      vehicle.licensePlate?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      vehicle.brand?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      vehicle.model?.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesStatus = filterStatus === 'ALL' || vehicle.status === filterStatus;
    
    return matchesSearch && matchesStatus;
  });

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="400px">
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box p={3}>
      <Box mb={3}>
        <Typography variant="h4" gutterBottom>
          车辆信息管理
        </Typography>
        
        {error && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {error}
          </Alert>
        )}
        
        <Box display="flex" gap={2} mb={2} flexWrap="wrap">
           <TextField
             label="搜索车辆"
             variant="outlined"
             size="small"
             value={searchTerm}
             onChange={(e) => setSearchTerm(e.target.value)}
             onKeyPress={(e) => e.key === 'Enter' && searchVehicles()}
             InputProps={{
               endAdornment: (
                 <IconButton onClick={searchVehicles}>
                   <SearchIcon />
                 </IconButton>
               ),
             }}
             sx={{ minWidth: 200 }}
           />
           
           <FormControl size="small" sx={{ minWidth: 120 }}>
             <InputLabel>状态筛选</InputLabel>
             <Select
               value={filterStatus}
               onChange={(e) => setFilterStatus(e.target.value)}
               label="状态筛选"
             >
               <MenuItem value="ALL">全部</MenuItem>
               <MenuItem value="ACTIVE">正常</MenuItem>
               <MenuItem value="STOLEN">被盗</MenuItem>
               <MenuItem value="MAINTENANCE">维修中</MenuItem>
               <MenuItem value="INACTIVE">停用</MenuItem>
             </Select>
           </FormControl>

           <Button
             variant="contained"
             color="primary"
             startIcon={<AddIcon />}
             onClick={() => navigate('/vehicles/add')}
             sx={{ ml: 'auto' }}
           >
             添加车辆
           </Button>
         </Box>
      </Box>

      {filteredVehicles.length === 0 ? (
        <Box textAlign="center" py={5}>
          <Typography variant="h6" color="textSecondary">
            暂无车辆信息
          </Typography>
        </Box>
      ) : (
        <Grid container spacing={3}>
          {filteredVehicles.map((vehicle) => (
            <Grid item xs={12} sm={6} md={4} lg={3} key={vehicle.id}>
              <Card sx={{ height: '100%' }}>
                <CardContent>
                  <Box display="flex" alignItems="center" mb={2}>
                    <Avatar sx={{ bgcolor: 'primary.main', mr: 2 }}>
                      <CarIcon />
                    </Avatar>
                    <Box flexGrow={1}>
                      <Typography variant="h6" component="h3">
                        {vehicle.brand} {vehicle.model}
                      </Typography>
                      <Typography variant="body2" color="textSecondary">
                        {vehicle.year}
                      </Typography>
                    </Box>
                    <Chip
                      label={getStatusLabel(vehicle.status)}
                      color={getStatusColor(vehicle.status)}
                      size="small"
                    />
                  </Box>

                  <Typography variant="body2" color="textSecondary" gutterBottom>
                    车牌号: {vehicle.licensePlate}
                  </Typography>
                  <Typography variant="body2" color="textSecondary" gutterBottom>
                    VIN: {vehicle.vin}
                  </Typography>
                  <Typography variant="body2" color="textSecondary" gutterBottom>
                    颜色: {vehicle.color}
                  </Typography>
                  <Typography variant="body2" color="textSecondary" gutterBottom>
                    里程: {vehicle.mileage?.toLocaleString()} km
                  </Typography>
                  <Typography variant="body2" color="textSecondary" gutterBottom>
                    车主: {vehicle.ownerName}
                  </Typography>
                  
                  {vehicle.tags && vehicle.tags.length > 0 && (
                    <Box mt={1}>
                      {vehicle.tags.map((tag, index) => (
                        <Chip
                          key={index}
                          label={tag}
                          size="small"
                          variant="outlined"
                          sx={{ mr: 0.5, mb: 0.5 }}
                        />
                      ))}
                    </Box>
                  )}

                  <Box mt={2} display="flex" justifyContent="space-between">
                    <Button
                      size="small"
                      color="primary"
                      onClick={() => navigate(`/vehicles/detail/${vehicle.id}`)}
                    >
                      详情
                    </Button>
                    <Button
                      size="small"
                      color="secondary"
                      onClick={() => navigate(`/vehicles/edit/${vehicle.id}`)}
                    >
                      编辑
                    </Button>
                  </Box>
                </CardContent>
              </Card>
            </Grid>
          ))}
        </Grid>
      )}

      {/* 车辆详情对话框 */}
      <Dialog open={openDialog} onClose={() => setOpenDialog(false)} maxWidth="md" fullWidth>
        <DialogTitle>车辆详细信息</DialogTitle>
        <DialogContent>
          {selectedVehicle && (
            <Box>
              <Typography variant="h6" gutterBottom>
                {selectedVehicle.brand} {selectedVehicle.model} ({selectedVehicle.year})
              </Typography>
              
              <Grid container spacing={2}>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    <strong>车牌号:</strong> {selectedVehicle.licensePlate}
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    <strong>VIN码:</strong> {selectedVehicle.vin}
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    <strong>车身颜色:</strong> {selectedVehicle.color}
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    <strong>车辆状态:</strong> {getStatusLabel(selectedVehicle.status)}
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    <strong>燃料类型:</strong> {selectedVehicle.fuelType}
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    <strong>变速箱:</strong> {selectedVehicle.transmissionType}
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    <strong>发动机排量:</strong> {selectedVehicle.engineCapacity}L
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    <strong>车辆类型:</strong> {selectedVehicle.vehicleType}
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    <strong>当前里程:</strong> {selectedVehicle.mileage?.toLocaleString()} km
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    <strong>注册日期:</strong> {new Date(selectedVehicle.registrationDate).toLocaleDateString()}
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    <strong>保险到期:</strong> {new Date(selectedVehicle.insuranceExpiry).toLocaleDateString()}
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    <strong>上次保养:</strong> {new Date(selectedVehicle.lastMaintenance).toLocaleDateString()}
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    <strong>下次保养:</strong> {selectedVehicle.nextMaintenanceDate ? new Date(selectedVehicle.nextMaintenanceDate).toLocaleDateString() : '-'}
                  </Typography>
                </Grid>
                <Grid item xs={12}>
                  <Typography variant="body1">
                    <strong>车主信息:</strong> {selectedVehicle.ownerName} - {selectedVehicle.ownerPhone}
                  </Typography>
                </Grid>
                <Grid item xs={12}>
                  <Typography variant="body1">
                    <strong>车主邮箱:</strong> {selectedVehicle.ownerEmail}
                  </Typography>
                </Grid>
                {selectedVehicle.notes && (
                  <Grid item xs={12}>
                    <Typography variant="body1">
                      <strong>备注:</strong> {selectedVehicle.notes}
                    </Typography>
                  </Grid>
                )}
              </Grid>

              {selectedVehicle.tags && selectedVehicle.tags.length > 0 && (
                <Box mt={2}>
                  <Typography variant="body1" gutterBottom>
                    <strong>标签:</strong>
                  </Typography>
                  <Box display="flex" flexWrap="wrap" gap={1}>
                    {selectedVehicle.tags.map((tag, index) => (
                      <Chip key={index} label={tag} size="small" />
                    ))}
                  </Box>
                </Box>
              )}
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenDialog(false)}>关闭</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default VehicleList;